package cn.whitecao.agent.plugin;

import cn.whitecao.agent.core.plugin.PluginMatcherRule;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
import net.bytebuddy.matcher.ElementMatchers;

import java.util.List;

/**
 * 切servlet的规则
 *
 * @author : BashfulHuang
 **/

public class ServletMatcherRule implements PluginMatcherRule {
    /**
     * 匹配类型
     *
     * @return ElementMatcher<TypeDescription>
     */
    @Override
    public ElementMatcher<TypeDescription> getTypesMatcher() {
        //切继承了HttpServlet的且不是抽象类的类
        ElementMatcher.Junction<TypeDescription> typeMatcher =
                ElementMatchers.hasSuperType(ElementMatchers.named("javax.servlet.http.HttpServlet"))
                .and(ElementMatchers.not(ElementMatchers.<TypeDescription>isAbstract()));
        return typeMatcher;
    }

    /**
     * 匹配方法
     * 切do开头的如doGet doPost doPut等,
     * 最好再判断一下来自是来自父类的
     *
     * @return ElementMatcher<MethodDescription>
     */
    @Override
    public ElementMatcher<MethodDescription> getMethodsMatcher() {

        return ElementMatchers.isMethod()
                //.and(ElementMatchers.isOverriddenFrom())
                .and(ElementMatchers.<MethodDescription>named("doService"))
                .and(ElementMatchers.takesArguments(2))
                .and(ElementMatchers.takesArgument(0, ElementMatchers.named("javax.servlet.http.HttpServletRequest")))
                .and(ElementMatchers.takesArgument(1, ElementMatchers.named("javax.servlet.http.HttpServletResponse")));

    }



}
